/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.boot.starter.logging.config;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.spi.AppenderAttachableImpl;
import io.iec.edp.caf.common.environment.EnvironmentUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.impl.StaticLoggerBinder;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;

import java.lang.reflect.Field;
import java.util.List;

/**
 *
 * @author wangyandong
 */
@Slf4j
public class CafLoggingApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        removeAppender();
    }

    private void removeAppender() {
        if (EnvironmentUtil.getProperty("ENABLE_CONSOLE_LOGGING", Boolean.class, Boolean.TRUE)) {
            return;
        }

        LoggerContext lc = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();
        Logger logger = lc.getLogger(Logger.ROOT_LOGGER_NAME);

        try {
            Field aaiField = Logger.class.getDeclaredField("aai");
            aaiField.setAccessible(true);
            AppenderAttachableImpl aai = (AppenderAttachableImpl) aaiField.get(logger);
            Field appenderListField = AppenderAttachableImpl.class.getDeclaredField("appenderList");
            appenderListField.setAccessible(true);
            List list = (List) appenderListField.get(aai);

            int index = -1;
            for (int i = 0; i < list.size(); i++) {
                Appender appender = (Appender) list.get(i);
                if (appender instanceof ConsoleAppender) {
                    index = i;
                    break;
                }
            }
            if(index>=0) {
                list.remove(0);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error(e.getMessage(),e);
        }
    }
}